<template>
  <el-dialog :title="dispatchType + '派工'" :visible.sync="dialogVisible" width="1300px" :before-close="close" class="distribute-dialog">
    <el-button type="primary" icon="el-icon-plus" @click="add()" v-if="$checkAuth('')">添加派工单</el-button>
    <div v-show="showAddDispatch">
      <div class="mt10 pl10 mb20">
        
        <span class="bold">选择工艺版本</span>
        <el-select v-model="curVersion" filterable clearable class="ml10" placeholder="选择工艺版本" @change="changeVersion">
          <template>
            <el-option v-for="(option,index) in versionList" :key="index" :label="option.versionName" :value="option"></el-option>
          </template>
        </el-select>
        <span class="bold ml20">派工单数量</span>
        <el-input-number v-model="submitData.dispatchNumber" @change="dispatchNumChange" placeholder="派工数量" size="small" class="w110 ml10" :min="0"></el-input-number>
        <el-switch v-model="submitData.cleanBySelf" active-text="自清整" inactive-text="专人清整" active-color="#004098" class="ml20" @change="cleanTypeChange"></el-switch>
        <el-button type="text" icon="el-icon-check" class="ml20" @click="save" :disabled="!curVersion">提交</el-button>
      </div>
      <el-table ref="articleTable" border stripe :data="versionDetail" row-key="sid" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="sequenceNumber" label="工序号" align="right" width="80"></el-table-column>
        <el-table-column prop="processName" label="工序名称" align="left" width="100"></el-table-column>
        <el-table-column prop="department" label="部门" align="left" width="80"></el-table-column>
        <el-table-column prop="supplier" label="供应商" align="left" min-width="80"></el-table-column>
        <el-table-column prop="dispatchNumber" label="工序数量" align="left" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.dispatchNumber" v-if="scope.row.processName" size="small" class="w110" :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="single" label="单双机" align="left" width="80">
          <template slot-scope="scope" v-if="scope.row.processName != '完工'">
            <div v-if="scope.row.department == '加工'">{{ scope.row.single ? '单机' : '双机' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="equipment" label="设备" align="left" width="100"></el-table-column>
        <el-table-column prop="quotaHour" label="定额工时" align="left" width="100"></el-table-column>
        <el-table-column prop="debugHour" label="调试工时" align="left" width="100"></el-table-column>
        <el-table-column label="是否调试" align="left" width="100">
          <template slot-scope="scope">
            <el-switch v-if="scope.row.department == '加工'" v-model="scope.row.debug" active-color="#13ce66"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="workerName" label="指派人" align="left" width="100"></el-table-column>
        <el-table-column label="操作" fixed="right" align="left" min-width="180">
          <template slot-scope="scope">
            <div v-if="scope.row.department == '加工'" @click="curProcessIndex = scope.row.sequenceNumber - 1">
              <el-dropdown @command="addEquipment" trigger="click">
                <span class="el-dropdown-link cursor-pointer"><i class="el-icon-plus"></i>添加设备<i class="el-icon-arrow-down el-icon--right"></i> </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in scope.row.equipmentList" :key="index" :command="item">{{ item.equipment }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div v-else-if="scope.row.equipment" @click="curEquipment = scope.row">
              <el-dropdown @command="addPerson" trigger="click">
                <span class="el-dropdown-link cursor-pointer"><i class="el-icon-plus"></i>添加指派人<i class="el-icon-arrow-down el-icon--right"></i> </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in scope.row.workerList" :key="index" :command="item">{{ item.workerName }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-tooltip content="移除该设备" placement="top-end" effect="light">
                <el-button class="el-icon-delete ml10" type="text" @click="delEquipment(scope.row.sid)"></el-button>
              </el-tooltip>
            </div>
            <div v-else-if="scope.row.workerName">
              <el-tooltip content="移除该指派人" placement="top-end" effect="light">
                <el-button class="el-icon-delete ml10" type="text" @click="delPerson(scope.row.sid)"></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 派工单列表 -->
    <div>
      <div class="bold fontSize16 mt20 mb10">派工单列表</div>
      <el-collapse accordion v-model="activeCollapseData"  @change="isEdit = false">
        <template>
          <el-collapse-item v-for="(dispatch,index) in dispatchList" :key="index" :name="dispatch.dispatchFormId">
            <template slot="title">
              <div class="flex justify-content-center">
                  <div class="w150">
                    <span class="fontSize14 bold">派工单号：</span>{{ dispatch.dispatchFormNumber }} 
                  </div>
                  <div class="w120">
                    <span class="pl15 fontSize14 bold">派工数量：</span>{{ dispatch.dispatchNumber }}
                  </div>
                  <div class="w200">
                    <span class="pl15 fontSize14 bold">派工时间：</span>{{ dispatch.createTime }}
                  </div> 
                  <div class="w120">
                    <span class="pl15 fontSize14 bold">完工数量：</span>{{ dispatch.finishedNumber }}
                  </div>
                  <div class="w200">
                    <span class="pl15 fontSize14 bold">完工时间：</span>{{ dispatch.finishTime }}
                  </div> 
                  <div class="w125">
                    <span class="pl15 fontSize14 bold">状态：</span>{{ dispatch.formState }}
                  </div>
                  <div>
                    <span class="pl15 fontSize14 bold">清整方式：</span>
                    <el-switch v-if="dispatch.isEdit" v-model="dispatch.cleanBySelf" active-text="自清整" inactive-text="专人清整" active-color="#004098" class="ml20"></el-switch>
                    <span v-else>{{ dispatch.cleanBySelf ? '自清整' : '专人清整' }}</span>
                  </div>
                </div>
            </template>
            <el-row>
              <span class="bold pr10">派工单</span>
              <el-button
                v-show="dispatch.isEdit"
                type="text"
                size="small"
                class="w50 mr20"
                icon="el-icon-close"
                @click="dispatch.isEdit = false"
              >取消变更</el-button>
              <el-button
                type="text"
                size="small"
                class="w50"
                :icon="dispatch.isEdit ? 'el-icon-check':'el-icon-edit'"
                :disabled="dispatch.formState != '进行中'"
                @click="editDispatch(dispatch)"
                v-if="$checkAuth(['dispatchUpdate'])"
              >{{ dispatch.isEdit ? '保存' : '变更'}}</el-button>
              <!-- <el-button
                type="text"
                size="small"
                class="w100"
                icon="el-icon-s-claim"
                :disabled="['已完工','异常终止'].includes(dispatch.formState)"
              >单双机审核</el-button> -->
              <el-button
                type="text"
                size="small"
                class="w80"
                icon="el-icon-check"
                :disabled="dispatch.isEdit || ['已完工','异常终止'].includes(dispatch.formState)"
                v-if="$checkAuth(['dispatchConfirm'])"
                @click="confirmCompleteDispatch(dispatch)"
              >完工确认</el-button>
              <el-button
                type="text"
                size="small"
                class="w50"
                icon="el-icon-warning-outline"
                :disabled="dispatch.isEdit || ['已完工','异常终止'].includes(dispatch.formState)" 
                v-if="$checkAuth(['dispatchStop'])"
                @click="terminateDispatch(dispatch)"
              >终止</el-button>
              <el-button
                type="text"
                size="small"
                :disabled="dispatch.isEdit"
                v-if="$checkAuth(['dispatchQrcode'])"
                @click="onClickQR(dispatch.dispatchFormId,dispatch.dispatchNumber)"
              >生成二维码</el-button>
            </el-row>
            <el-table
              border
              stripe
              class="mb10"
              :data="dispatch.processList"
              row-key="sid"
              default-expand-all 
              v-show="!dispatch.isEdit"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
              <el-table-column prop="sequenceNumber" label="工序号" align="right" width="80"></el-table-column>
              <el-table-column prop="processName" label="工序名称" align="center" width="100"></el-table-column>
              <el-table-column prop="department" label="部门" align="center" width="100"></el-table-column>
              <el-table-column prop="totalNumber" label="工序数量" align="center" width="100">
                <template slot-scope="scope">
                  <input v-if="scope.row.processstate=='未开始'&& dispatch.isEdit" class="w50"  v-model="scope.row.dispatchNumber" />
                  <span v-else>{{scope.row.dispatchNumber}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="single" label="单双机" align="center" width="75">
                <template slot-scope="scope">
                  <span v-if="scope.row.department == '加工'">{{ scope.row.single ? '单机' : '双机' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="debug" label="是否调试" align="center" width="100">
                <template slot-scope="scope" v-if="scope.row.department == '加工'">
                  {{ scope.row.debug ? '是' : '否'}}
                </template>
              </el-table-column>
              <el-table-column prop="equipment" label="设备" align="center" width="75"></el-table-column>
              <el-table-column prop="quotaHour" label="定额工时" align="center" width="80"></el-table-column>
              <el-table-column prop="debugHour" label="调试工时" align="center" width="80"></el-table-column>
              <el-table-column prop="workerName" label="指派(完工)人" align="center" width="125"></el-table-column>
              <el-table-column
                prop="workerNumber"
                label="完工数量"
                align="center"
                width="100"
              >
              </el-table-column>
              <el-table-column prop="realWorkHour" label="实动工时" align="center" width="80"></el-table-column>
              <el-table-column prop="numberQualified" label="合格" align="center" width="80"></el-table-column>
              <el-table-column prop="numberPending" label="待处理" align="center" width="80"></el-table-column>
              <el-table-column
                prop="numberWasteIndustrial"
                label="工废"
                align="center"
                width="80"
              ></el-table-column>
              <el-table-column
                prop="numberWasteMaterial"
                label="废料"
                align="center"
                width="80"
              ></el-table-column>
              <el-table-column prop="numberRework" label="返工" align="center" width="80"></el-table-column>
              <el-table-column prop="processstate" label="质检确认" align="center" width="100"></el-table-column>
              <el-table-column label="单双机审核" align="center" width="80" v-if="!noSingleReview && $checkAuth(['dispatchSingle'])">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-s-claim"
                    v-if="scope.row.processstate == '单双机审核'"
                    :disabled="['已完工','异常终止'].includes(dispatch.formState)"
                  >审核</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table ref="articleTable" border stripe :data="tempProcessList" row-key="sid" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-show="dispatch.isEdit">
              <el-table-column prop="sequenceNumber" label="工序号" align="right" width="80"></el-table-column>
              <el-table-column prop="processName" label="工序名称" align="left" width="100"></el-table-column>
              <el-table-column prop="department" label="部门" align="left" width="80"></el-table-column>
              <el-table-column prop="supplier" label="供应商" align="left" min-width="80"></el-table-column>
              <el-table-column prop="dispatchNumber" label="工序数量" align="left" width="150">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.dispatchNumber" v-if="scope.row.processName" size="small" class="w110" :min="0" :disabled="scope.row.canEdit != true"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="single" label="单双机" align="left" width="80">
                <template slot-scope="scope" v-if="scope.row.processName != '完工'">
                  <div v-if="scope.row.department == '加工'">{{ scope.row.single ? '单机' : '双机' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="equipment" label="设备" align="left" width="100"></el-table-column>
              <el-table-column prop="quotaHour" label="定额工时" align="left" width="100"></el-table-column>
              <el-table-column prop="debugHour" label="调试工时" align="left" width="100"></el-table-column>
              <el-table-column label="是否调试" align="left" width="100">
                <template slot-scope="scope">
                  <el-switch v-if="scope.row.department == '加工'" v-model="scope.row.debug" active-color="#13ce66" :disabled="scope.row.canEdit != true"></el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="workerName" label="指派人" align="left" width="100"></el-table-column>
              <el-table-column label="操作" fixed="right" align="left" min-width="180">
                <template slot-scope="scope" v-if="scope.row.canEdit == true">
                  <div v-if="scope.row.department == '加工'" @click="tempProcessIndex = scope.row.sequenceNumber - 1">
                    <el-dropdown @command="addTempEquipment" trigger="click">
                      <span class="el-dropdown-link cursor-pointer"><i class="el-icon-plus"></i>添加设备<i class="el-icon-arrow-down el-icon--right"></i> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="(item, index) in scope.row.equipmentList" :key="index" :command="item">{{ item.equipment }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                  <div v-else-if="scope.row.equipment" @click="curEquipment = scope.row">
                    <el-dropdown @command="addTempPerson" trigger="click">
                      <span class="el-dropdown-link cursor-pointer"><i class="el-icon-plus"></i>添加指派人<i class="el-icon-arrow-down el-icon--right"></i> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="(item, index) in scope.row.workerList" :key="index" :command="item">{{ item.workerName }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <el-tooltip content="移除该设备" placement="top-end" effect="light">
                      <el-button class="el-icon-delete ml10" type="text" @click="delTempEquipment(scope.row.sid)"></el-button>
                    </el-tooltip>
                  </div>
                  <div v-else-if="scope.row.workerName">
                    <el-tooltip content="移除该指派人" placement="top-end" effect="light">
                      <el-button class="el-icon-delete ml10" type="text" @click="delTempPerson(scope.row.sid)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </template>
      </el-collapse>
      <QR ref="qr"></QR>
      <no-data placeholder="还没有派工单，快去添加吧~" v-if="dispatchList.length == 0"></no-data>
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash'
import { qrcodeDispatch, getDispatchPV, getDispatchDetail, createDispatch, updateDispatch, confirmDispatch, stopDispatch } from '@/api/dispatch' // 获取产品上的设计工艺版本
import { Notification, Message } from 'element-ui'
import QR from '../qr.vue'
export default {
  name: 'distribute',
  data() {
    return {
      dispatchType: '生产',
      dialogVisible: false,
      curVersion: null, // 用来在选择工艺版本的时候记录现在的工艺版本
      curProcessIndex: -1, // 用来在添加设备/人员的时候找到该工序
      curEquipment: null, // 用来添加指派人的时候保存设备对象
      versionList: [], // 产品可选的工艺版本列表
      versionDetail: [], // 当前选中的工艺版本，以此作为模板设计派工单
      addDispatch: false, // 记录当前是否处于添加派工单状态
      dot: ';',
      submitData: {
        producingId: '', // 产品生产ID
        dispatchNumber: 0, // 派工单派工数量
        versionId: '', // 工艺版本ID
        cleanBySelf: true, // 自清整/专人清整
        processList: [] // 派工工序列表
      },
      dispatchList: [],
      showAddDispatch: false,
      activeCollapseData: null,
      isEdit: false, // false:变更 true:保存
      noSingleReview: true, // 没有需要单双机审核的工序
      tempProcessList: [],
      tempProcessIndex: -1,
      tempVersion: []
    }
  },
  methods: {
    async open(producingId, type = '生产') {
      this.submitData.producingId = producingId
      this.dispatchType = type
      let resp = await getDispatchPV({ producingId: producingId }).catch(err => {
        Notification.error(err)
      })
      if (resp) {
        this.versionList = resp.data
        this.getDispatchList()
        this.dialogVisible = true
      }
    },
    add() {
      this.initial()
      this.showAddDispatch = true
    },
    changeVersion(version) {
      if (version) {
        // 选中某一个版本
        this.submitData.versionId = version.versionId
        let processList = _.cloneDeep(version.processList)
        processList = processList.map((pItem, pIndex) => {
          this.$set(pItem, 'sid', 'a' + this.dot + pIndex)
          this.$set(pItem, 'debug', false) // 是否需要调试
          this.$set(pItem, 'dispatchNumber', 0)
          return pItem
        })
        this.versionDetail = processList
        // 默认自清整，如果有清整工序，则专人清整
        this.submitData.cleanBySelf = true
        for (let i = 0; i < processList.length; i++) {
          if (processList[i].processName == '清整') {
            this.submitData.cleanBySelf = false
          }
        }
      } else {
        this.initial()
      }
    },
    dispatchNumChange(value) {
      this.versionDetail = this.versionDetail.map(item => {
        item.dispatchNumber = value
        return item
      })
    },
    cleanTypeChange(value) {
      console.log('清整方式改变')
      console.log(value)
      // 如果选择自清整，需要判断工序中是否有清整工序，如果有清整工序仍派人自清整，则需要弹框确认
      if (value == true) {
        for (let i = 0; i < this.versionDetail.length; i++) {
          if (this.versionDetail[i].processName == '清整') {
            this.$confirm('工艺表中有清整工序，是否指派为专人清整？', '操作提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                this.submitData.cleanBySelf = true
              })
              .catch(() => {
                this.submitData.cleanBySelf = false
              })
          }
        }
      }
    },
    addEquipment(data) {
      let equip = _.cloneDeep(data)
      if (typeof this.versionDetail[this.curProcessIndex].children == 'undefined') {
        this.$set(this.versionDetail[this.curProcessIndex], 'children', [])
      }
      let flag = false
      this.versionDetail[this.curProcessIndex].children.forEach(item => {
        if (item.equipment === data.equipment) {
          flag = true
        }
      })
      if (flag) {
        Message.warning('请勿添加重复设备!')
        return
      }
      let eIndex = this.versionDetail[this.curProcessIndex].children.length
      equip.sid = 'b' + this.dot + this.curProcessIndex + this.dot + eIndex
      this.versionDetail[this.curProcessIndex].children.push(_.cloneDeep(equip))
    },
    delEquipment(sid) {
      let info = sid.split(this.dot) // info=[a:工序列表的Index;b:设备的index;c:工人的index]
      this.versionDetail[info[1]].children.splice(info[2], 1) // 删除设备
      this.resetSid()
    },
    addPerson(data) {
      let person = _.cloneDeep(data)
      if (typeof this.curEquipment.children == 'undefined') {
        this.$set(this.curEquipment, 'children', [])
      }
      let flag = false
      this.curEquipment.children.forEach(item => {
        if (item.workerName === data.workerName) {
          flag = true
        }
      })
      if (flag) {
        Message.warning('请勿添加重复人员!')
        return
      }
      let pIndex = this.curEquipment.sid.split(this.dot)[1]
      let eIndex = this.curEquipment.sid.split(this.dot)[2]
      let wIndex = this.curEquipment.children.length
      person.sid = 'c' + this.dot + pIndex + this.dot + eIndex + this.dot + wIndex
      this.curEquipment.children.push(person)
    },
    delPerson(sid) {
      let info = sid.split(this.dot)
      this.versionDetail[info[1]].children[info[2]].children.splice(info[3], 1)
      this.resetSid()
    },
    resetSid() {
      this.versionDetail = this.versionDetail.map((item, index) => {
        if (item.children) {
          item.children = item.children.map((cItem, cIndex) => {
            if (cItem.children) {
              cItem.children = cItem.children.map((wItem, wIndex) => {
                wItem.sid = 'c' + this.dot + index + this.dot + cIndex + this.dot + wIndex
                return wItem
              })
            }
            cItem.sid = 'b' + this.dot + index + this.dot + cIndex
            return cItem
          })
        }
        return item
      })
    },
    resetSidDispatch() {
      this.dispatchList = this.dispatchList.map(dItem => {
        this.$set(dItem, 'isEdit', false)
        dItem.processList = dItem.processList.map((item, index) => {
          if (item.processstate == '单双机审核') {
            this.noSingleReview = false
          }
          if (item.children && item.children.length) {
            item.children = item.children.map((cItem, cIndex) => {
              if (cItem.children) {
                cItem.children = cItem.children.map((wItem, wIndex) => {
                  wItem.sid = 'c' + this.dot + index + this.dot + cIndex + this.dot + wIndex
                  return wItem
                })
              }
              cItem.sid = 'b' + this.dot + index + this.dot + cIndex
              return cItem
            })
          } else {
            this.$delete(item, 'children')
          }
          return item
        })
        return dItem
      })
    },
    resetSidTempDispatch() {
      this.tempProcessList = this.tempProcessList.map((item, index) => {
        if (item.children && item.children.length) {
          item.children = item.children.map((cItem, cIndex) => {
            if (cItem.children) {
              cItem.children = cItem.children.map((wItem, wIndex) => {
                wItem.sid = 'c' + this.dot + index + this.dot + cIndex + this.dot + wIndex
                return wItem
              })
            }
            cItem.sid = 'b' + this.dot + index + this.dot + cIndex
            return cItem
          })
        }
        return item
      })
    },
    addTempEquipment(data) {
      let equip = _.cloneDeep(data)
      if (typeof this.tempProcessList[this.tempProcessIndex].children == 'undefined') {
        this.$set(this.tempProcessList[this.tempProcessIndex], 'children', [])
      }
      let eIndex = this.tempProcessList[this.tempProcessIndex].children.length
      equip.sid = 'b' + this.dot + this.tempProcessIndex + this.dot + eIndex
      equip.canEdit = true
      this.tempProcessList[this.tempProcessIndex].children.push(_.cloneDeep(equip))
    },
    delTempEquipment(sid) {
      let info = sid.split(this.dot) // info=[a:工序/b:设备/c:工人,工序列表的Index,设备的index,工人的index}
      this.tempProcessList[info[1]].children.splice(info[2], 1) // 删除设备
      this.resetSidTempDispatch()
    },
    addTempPerson(data) {
      let person = _.cloneDeep(data)
      if (typeof this.curEquipment.children == 'undefined') {
        this.$set(this.curEquipment, 'children', [])
      }
      let pIndex = this.curEquipment.sid.split(this.dot)[1]
      let eIndex = this.curEquipment.sid.split(this.dot)[2]
      let wIndex = this.curEquipment.children.length
      person.sid = 'c' + this.dot + pIndex + this.dot + eIndex + this.dot + wIndex
      person.canEdit = true
      this.curEquipment.children.push(person)
    },
    delTempPerson(sid) {
      let info = sid.split(this.dot)
      this.tempProcessList[info[1]].children[info[2]].children.splice(info[3], 1)
      this.resetSidTempDispatch()
    },
    initial() {
      this.curVersion = null
      this.curProcessIndex = -1
      this.versionDetail = []
      this.submitData.dispatchNumber = 0
      this.submitData.versionId = ''
      this.submitData.processList = []
      this.activeCollapseData = null
    },
    close(done) {
      if (this.curVersion) {
        this.$confirm(`您还有未提交的派工单信息，退出将不会保存该信息，是否确认退出？`, '退出提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            this.initial()
            this.versionList = []
            this.dispatchList = []
            this.showAddDispatch = false
            this.dialogVisible = false
            done()
          })
          .catch(() => {})
      } else {
        this.initial()
        this.versionList = []
        this.dispatchList = []
        this.showAddDispatch = false
        this.dialogVisible = false
        done()
      }
    },
    // 提交派工单
    save() {
      if (!this.submitData.dispatchNumber) return Notification.error('派工单数量不能为零！')
      let complete = true // 是否已经填写完整的派工单
      let message = ''
      let processList = _.cloneDeep(this.versionDetail)
      this.submitData.processList = processList.map((pItem, pIndex) => {
        delete pItem.sid
        pItem.processSequenceId = pItem.sequenceId
        if (pItem.children && pItem.children.length > 0) {
          pItem.children = pItem.children.map((eItem, eIndex) => {
            delete eItem.sid
            delete eItem.sequenceId
            if (eItem.children && eItem.children.length > 0) {
              eItem.children = eItem.children.map(wItem => {
                delete wItem.sid
                return wItem
              })
              // delete eItem.workerList
            } else {
              complete = false
              message = `第 ${pIndex + 1} 道工序存在没有添加指派人的设备,请先添加指派人!`
            }
            return eItem
          })
        } else if (pItem.department == '加工') {
          // 既没有children还是加工工序，也就是加工工序没有设备
          complete = false
          message = `第 ${pIndex + 1} 道工序还没有添加设备,请先添加设备!`
        }
        delete pItem.sequenceId
        // delete pItem.equipmentList
        return pItem
      })
      if (complete) {
        console.log('确实可以提交了')
        this.submitDispatch(this.submitData)
      } else {
        Notification.error(message)
      }
    },
    async submitDispatch(data) {
      let res = await createDispatch(data).catch(err => {
        Notification.error(err)
      })
      if (res) {
        Message.success('新建派工单成功!')
        this.initial()
        this.showAddDispatch = false
        this.getDispatchList()
      }
    },
    async getDispatchList() {
      let res = await getDispatchDetail({ producingId: this.submitData.producingId }).catch(err => {
        Notification.error(err)
      })
      if (res) {
        this.dispatchList = res.data
        this.resetSidDispatch()
      }
    },
    // 变更派工单--变更条件(formState==派工异常)--可变更内容(未开始的工序的工序数量)
    async editDispatch(dispatch) {
      if (dispatch.isEdit) {
        // 点击保存
        this.submitData.dispatchFormId = dispatch.dispatchFormId
        this.submitData.producingId = dispatch.producingId
        this.submitData.versionId = dispatch.versionId
        this.submitData.cleanBySelf = dispatch.cleanBySelf // 是否有必要修改？？
        this.submitData.processList = this.tempProcessList.filter(item => {
          return item.processstate == '未开始'
        })
        let res = await updateDispatch(this.submitData).catch(err => {
          console.log('变更不成功', err)
          Notification.error(err)
        })
        if (res) {
          dispatch.isEdit = !dispatch.isEdit
          this.getDispatchList()
        }
      } else {
        // 点击变更按钮
        this.tempProcessList = _.cloneDeep(dispatch.processList)
        // 设置'canEdit' 用来判断哪些数据可以变更
        this.tempProcessList = this.tempProcessList.map((pItem, pIndex) => {
          if (pItem.processstate == '未开始') {
            pItem.canEdit = true
            if (pItem.children) {
              pItem.children = pItem.children.map(eItem => {
                eItem.canEdit = true
                if (eItem.children) {
                  eItem.children = eItem.children.map(wItem => {
                    wItem.canEdit = true
                    return wItem
                  })
                }
                return eItem
              })
            }
          }
          return pItem
        })
        // 设置变更后可选的设备和人员列表
        this.tempVersion = this.versionList.find(item => {
          return item.versionId == dispatch.versionId
        })
        // 设置变更后可选的设备和人员列表
        if (this.tempVersion.processList) {
          this.tempVersion.processList.forEach((item, index) => {
            if (item.equipmentList) {
              this.tempProcessList[index].equipmentList = item.equipmentList
              item.equipmentList.forEach((eItem, eIndex) => {
                this.tempProcessList[index].children.forEach((cItem, cIndex) => {
                  if (eItem.equipHourId == cItem.equipHourId) {
                    cItem.workerList = eItem.workerList
                  }
                })
              })
            }
          })
        }
        dispatch.isEdit = !dispatch.isEdit
      }
    },

    async confirmCompleteDispatch(dispatch) {
      let flag = true
      dispatch.processList.forEach(item => {
        if (item.state == 0) {
          flag = false // 有未开始的工序
          return
        }
      })
      if (flag) {
        let res = await confirmDispatch({ dispatchFormId: dispatch.dispatchFormId }).catch(err => {
          Notification.error(err)
        })
        if (res) {
          Message.success('已确认完工!')
          this.getDispatchList()
        }
      } else {
        Notification.error('还有未开始的工序，不予完工')
      }
    },

    terminateDispatch(dispatch) {
      const stopParam = {
        dispatchFormId: Number(dispatch.dispatchFormId),
        remark: ''
      }
      this.$prompt('请输入事由', `终止派工单${dispatch.dispatchFormNumber}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(({ value }) => {
          console.log('点击了确定')
          console.log(value)
          stopParam.remark = '' + value
          this.onStopDispatch(stopParam)
        })
        .catch(() => {
          console.log('点击了取消')
          this.$message({
            type: 'info',
            message: '取消终止'
          })
        })
      // this.$confirm(`是否确认终止派工单${dispatch.dispatchFormNumber}?`, '操作提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(async () => {
      //     let res = await stopDispatch({dispatchFormId: dispatch.dispatchFormId}).catch(err => {
      //       Notification.error(err)
      //     })
      //     if(res) {
      //       Message.success('已终止派工单!')
      //       this.getDispatchList()
      //     }
      //   }).catch(() => {})
    },

    async onStopDispatch(stopParam) {
      let res = await stopDispatch(stopParam).catch(err => {
        Notification.error(err)
      })
      if (res) {
        Message.success('已终止派工单!')
        this.getDispatchList()
      }
    },

    onClickQR(id, dispatchNumber) {
      window.open('/dispatch/qrcode?dispatchFormId=' + id)
      // this.getQRCode(id);
      // this.$refs.qr.open(id, dispatchNumber)
    },
    async getQRCode(id) {
      let res = await qrcodeDispatch({ dispatchFormId: id })
        .then(res => {
          var filename = res.headers //下载后文件名
          filename = filename['content-disposition']
          filename = decodeURI(filename.split(';')[1].split('filename=')[1])
          var blob = new Blob([res.data], { type: 'image/png' })
          var downloadElement = document.createElement('a')
          var href = URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = filename
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(err => {
          console.log('qrcode err')
          console.log(err)
        })
    }
  },
  components: {
    QR
  }
}
</script>

<style lang="scss">
.distribute-dialog {
  .el-dropdown-menu {
    min-width: 100px !important;
  }
  .w110 {
    width: 110px;
  }
  .el-dialog {
    min-height: 200px;
  }
  .el-switch__label.is-active > span {
    font-weight: bold;
    font-size: 18px;
  }
}
</style>